import 'package:flutter/foundation.dart';
import '../models/directory_model.dart';
import '../services/directory_service.dart';

/// 目录缓存服务，用于缓存设备-相册目录结构及其ID
class DirectoryCacheService {
  // 单例模式
  static final DirectoryCacheService _instance =
      DirectoryCacheService._internal();
  factory DirectoryCacheService() => _instance;
  DirectoryCacheService._internal();

  // 目录服务
  final DirectoryService _directoryService = DirectoryService();

  // 设备根目录缓存 (设备名 -> 目录ID)
  final Map<String, int> _deviceDirectoryCache = {};

  // 相册目录缓存 (设备ID_相册名 -> 目录ID)
  final Map<String, int> _albumDirectoryCache = {};

  // 目录是否已初始化
  bool _isInitialized = false;

  /// 获取设备根目录ID，如果不存在则创建
  Future<int> getOrCreateDeviceDirectory(String deviceName) async {
    if (deviceName.trim().isEmpty) {
      debugPrint('错误: 设备名称为空，无法创建设备目录');
      throw Exception('设备名称不能为空');
    }

    debugPrint('准备获取或创建设备目录: $deviceName');

    // 检查缓存中是否存在
    if (_deviceDirectoryCache.containsKey(deviceName)) {
      debugPrint('使用缓存的设备目录ID: ${_deviceDirectoryCache[deviceName]}');
      return _deviceDirectoryCache[deviceName]!;
    }

    try {
      // 先尝试查找设备目录是否已存在
      final existingDirectory = await _directoryService.findDirectory(
        deviceName,
      );

      if (existingDirectory != null) {
        // 目录已存在，缓存并返回
        final directoryId = existingDirectory.id;
        _deviceDirectoryCache[deviceName] = directoryId;
        debugPrint('找到现有设备目录: $deviceName, ID: $directoryId');
        return directoryId;
      }

      // 目录不存在，创建新目录
      debugPrint('设备目录不存在，创建新目录: $deviceName');
      final directory = await _directoryService.createDirectory(deviceName);
      final directoryId = directory.id;

      // 将结果保存到缓存
      _deviceDirectoryCache[deviceName] = directoryId;

      debugPrint('成功创建设备目录: $deviceName, ID: $directoryId');
      return directoryId;
    } catch (e) {
      debugPrint('获取或创建设备目录失败: $e');
      rethrow;
    }
  }

  /// 获取相册目录ID，如果不存在则创建
  Future<int> getOrCreateAlbumDirectory(
    String deviceName,
    String albumName,
  ) async {
    if (deviceName.trim().isEmpty) {
      debugPrint('错误: 设备名称为空，无法创建相册目录');
      throw Exception('设备名称不能为空');
    }

    if (albumName.trim().isEmpty) {
      debugPrint('错误: 相册名称为空，无法创建相册目录');
      throw Exception('相册名称不能为空');
    }

    debugPrint('准备获取或创建相册目录: 设备[$deviceName], 相册[$albumName]');

    // 缓存键
    final cacheKey = '$deviceName/$albumName';

    // 检查缓存中是否存在
    if (_albumDirectoryCache.containsKey(cacheKey)) {
      debugPrint('使用缓存的相册目录ID: ${_albumDirectoryCache[cacheKey]}');
      return _albumDirectoryCache[cacheKey]!;
    }

    try {
      // 获取设备目录ID
      final deviceDirectoryId = await getOrCreateDeviceDirectory(deviceName);

      // 先尝试查找相册目录是否已存在
      final existingDirectory = await _directoryService.findDirectory(
        albumName,
        parentId: deviceDirectoryId,
      );

      if (existingDirectory != null) {
        // 目录已存在，缓存并返回
        final directoryId = existingDirectory.id;
        _albumDirectoryCache[cacheKey] = directoryId;
        debugPrint('找到现有相册目录: $cacheKey, ID: $directoryId');
        return directoryId;
      }

      // 目录不存在，创建相册目录
      debugPrint('相册目录不存在，创建新目录: $albumName');
      final directory = await _directoryService.createDirectory(
        albumName,
        parentId: deviceDirectoryId,
      );
      final directoryId = directory.id;

      // 将结果保存到缓存
      _albumDirectoryCache[cacheKey] = directoryId;

      debugPrint('成功创建相册目录: $cacheKey, ID: $directoryId');
      return directoryId;
    } catch (e) {
      debugPrint('获取或创建相册目录失败: $e');
      rethrow;
    }
  }

  /// 处理子相册目录结构
  Future<int> getOrCreateSubAlbumDirectory(
    String deviceName,
    String parentAlbumName,
    String albumName,
  ) async {
    if (deviceName.trim().isEmpty) {
      debugPrint('错误: 设备名称为空，无法创建子相册目录');
      throw Exception('设备名称不能为空');
    }

    if (parentAlbumName.trim().isEmpty) {
      debugPrint('错误: 父相册名称为空，无法创建子相册目录');
      throw Exception('父相册名称不能为空');
    }

    if (albumName.trim().isEmpty) {
      debugPrint('错误: 子相册名称为空，无法创建子相册目录');
      throw Exception('子相册名称不能为空');
    }

    // 生成缓存键
    final String cacheKey = '$deviceName/$parentAlbumName/$albumName';
    debugPrint('准备获取或创建子相册目录: $cacheKey');

    // 如果已经缓存，直接返回
    if (_albumDirectoryCache.containsKey(cacheKey)) {
      debugPrint('使用缓存的子相册目录ID: ${_albumDirectoryCache[cacheKey]}');
      return _albumDirectoryCache[cacheKey]!;
    }

    try {
      // 先确保父相册目录存在
      final int parentAlbumDirectoryId = await getOrCreateAlbumDirectory(
        deviceName,
        parentAlbumName,
      );

      // 检查子相册目录是否已存在
      final existingDirectory = await _directoryService.findDirectory(
        albumName,
        parentId: parentAlbumDirectoryId,
      );

      if (existingDirectory != null) {
        // 子相册目录已存在，缓存并返回
        final directoryId = existingDirectory.id;
        _albumDirectoryCache[cacheKey] = directoryId;
        debugPrint('找到现有子相册目录: $cacheKey, ID: $directoryId');
        return directoryId;
      }

      // 子相册目录不存在，创建新目录
      debugPrint('子相册目录不存在，创建新目录: $albumName');
      final directory = await _directoryService.createDirectory(
        albumName,
        parentId: parentAlbumDirectoryId,
      );

      final directoryId = directory.id;

      // 缓存目录ID
      _albumDirectoryCache[cacheKey] = directoryId;

      debugPrint('成功创建子相册目录: $cacheKey, ID: $directoryId');
      return directoryId;
    } catch (e) {
      debugPrint('获取或创建子相册目录失败: $e');
      rethrow;
    }
  }

  /// 清空缓存
  void clearCache() {
    _deviceDirectoryCache.clear();
    _albumDirectoryCache.clear();
    _isInitialized = false;
  }

  /// 缓存是否已初始化
  bool get isInitialized => _isInitialized;
}
